import 'dart:io';

import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/company/company_detail/company_detail_page.dart';
import 'package:e_reception_flutter/ui/company/company_register/bean/company_register_upload_bean.dart';
import 'package:e_reception_flutter/ui/company/company_register/widgets/company_register_success_page.dart';
import 'package:e_reception_flutter/ui/index/even/clear_index_company_info_event.dart';
import 'package:e_reception_flutter/ui/index/index_page.dart';
import 'package:e_reception_flutter/ui/login/login_bean/login_search_organization_bean.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:package_info/package_info.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

///用户登录服务接口请求
class UserLoginService {
  ///验证码登录接口
  static const String APP_USER_CODE_LOGIN_API =
     ServerApi.BASE_URL + "app/appUserCodeLogin";

  ///自动登录接口
  static const String APP_AUTO_LOGIN_API =
     ServerApi.BASE_URL + "app/appUserAgainLogin";

  ///公司注册接口
  static const String COMPANY_REGISTER_API =
     ServerApi.BASE_URL + "app/appCompanyRegistion";

  ///机构数据倒入接口
  static const String COMPANY_IMPORT_ORG_API =
     ServerApi.BASE_URL + "app/importOrgLogin";


  final VgBaseCallback<UserDataBean> callback;

  UserLoginService(this.callback):assert(callback != null);

  ///根据验证码登录
  Future<void> loginByCode(
      String phone, String code) async {
    if (callback == null) {
      return;
    }
    if (StringUtils.isEmpty(phone)) {
      callback?.onError("手机号不能为空");
      return;
    }

    if (phone.length != DEFAULT_PHONE_LENGTH_LIMIT) {
      callback?.onError("手机号长度不正确");
      return;
    }
    if (StringUtils.isEmpty(code)) {
      callback?.onError("验证码不能为空");
      return;
    }
    if (code.length != DEFAULT_AUTH_LENGTH_LIMIT) {
      callback?.onError("验证码不正确");
      return;
    }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo?.version;
    print("app version0:" + version.toString());
    VgHttpUtils.get(APP_USER_CODE_LOGIN_API,
        params: {
          "phone": globalSubPhone(phone) ?? "",
          "code": code ?? "",
          "sys": Platform.isAndroid?"01":"02",
          "versons": version ?? "0",
        },
        callback: BaseCallback(onSuccess: (val) {
          UserResponseBean responseBean = UserResponseBean.fromMap(val);
          if(responseBean == null || responseBean.data == null || responseBean.data.authId == null){
            callback?.onError("数据返回报错～");
            return;
          }
          if(responseBean?.data?.companyInfo?.isNeedForceLogout()??false){
            _doForceLogout();
            return;
          }
          callback?.onSuccess(responseBean?.data);
        }, onError: (msg) {
          callback?.onError(msg);
        }));
  }

  ///自动登录
  Future<void> autoLogin() async {
    if (callback == null) {
      return;
    }
    String authId = UserRepository.getInstance().authId ?? "";
    if(StringUtils.isEmpty(authId)){
      callback?.onError("未登录");
      return;
    }
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String version = packageInfo?.version;
    print(" app version1:" + version.toString());
    VgHttpUtils.get(APP_AUTO_LOGIN_API,
        params: {
          "authId": authId ?? "",
          "sys": Platform.isAndroid?"01":"02",
          "versons": version ?? "0",
        },
        callback: BaseCallback(onSuccess: (val) {
          UserResponseBean responseBean = UserResponseBean.fromMap(val);
          if(responseBean != null && responseBean?.success == false && "用户不存在" == (responseBean?.msg??"")){
            _doForceLogout();
            return;
          }
          if(responseBean == null || responseBean.data == null || responseBean.data.authId == null){
            callback?.onError("数据返回报错～");
            return;
          }
          if(responseBean?.data?.companyInfo?.isNeedForceLogout()??false){
            _doForceLogout();
            return;
          }
          SharePreferenceUtil.putInt(IndexPage.AUTO_LOGIN_TIME, DateTime.now().millisecondsSinceEpoch);
          callback?.onSuccess(responseBean?.data);
        }, onError: (msg) {
          callback?.onError(msg);
          if("用户不存在" == (msg??"")){
            _doForceLogout();
          }
        }));
  }


  void companyRegisterLogin(CompanyRegisterUploadBean uploadBean){
    VgHttpUtils.get(COMPANY_REGISTER_API,
        params: {
          "city":
          VgLocationUtils.encodeLocationByMap(uploadBean?.locationMap) ??
              "",
          "code": uploadBean?.authCode ?? "",
          "companyNick": uploadBean?.companyNick ?? "",
          "storeName": uploadBean?.storeName ?? "",
          "name": uploadBean?.name ?? "",
          "phone": globalSubPhone(uploadBean?.phone) ?? "",
          "companyName": uploadBean?.companyName ?? "",
          "address": uploadBean?.detailAddress ?? "",
          "gps": uploadBean?.gps ?? "",
          "type": uploadBean?.typeBean?.getType() ?? "00",
          "trade": uploadBean?.typeBean?.getTrade() ?? "00",
          "addrProvince": uploadBean?.locationMap[CHOOSE_PROVINCE_KEY]?.sname ?? "",
          "addrCity": uploadBean?.locationMap[CHOOSE_CITY_KEY]?.sname ?? "",
          "addrDistrict":uploadBean?.locationMap[CHOOSE_DISTRICT_KEY]?.sname ?? "",
          "addrCode":uploadBean?.locationMap[CHOOSE_DISTRICT_KEY]?.sid ?? "",
          "registionedition": uploadBean?.registionedition ?? "00",
          "backup": uploadBean?.backup ?? ""
        },
        callback: BaseCallback(onSuccess: (val) {
          UserResponseBean responseBean = UserResponseBean.fromMap(val);
          if(responseBean == null || responseBean.data == null || responseBean.data.authId == null){
            callback?.onError("数据返回报错～");
            return;
          }
          if(responseBean?.data?.companyInfo?.isNeedForceLogout()??false){
            _doForceLogout();
            return;
          }
          callback?.onSuccess(responseBean?.data);
          Future.delayed(Duration(seconds: 0),(){
            CompanyRegisterSuccessPage.navigatorPush(AppMain.context,uploadBean?.phone);
          });
          // Future.delayed(Duration(milliseconds: 1000),(){
          // CompanyRegisterSuccessDialog.navigatorPushDialog(AppMain.context);
          // });
        }, onError: (msg) {
          callback?.onError(msg);
        }));
  }

  void companyImportOrgLogin(BuildContext context,String phone, String code,OrgInfoListBean uploadBean){
    Future.delayed(Duration(seconds: 0),(){
      CompanyDetailPage.navigatorPush(AppMain.context,uploadBean.gps);
    });
    VgHudUtils.show(AppMain.context, "数据同步中");
    VgHttpUtils.get(COMPANY_IMPORT_ORG_API,
        params: {
          "addr_city":uploadBean?.city ?? "",
          "addr_code":uploadBean?.citycode ?? "",
          "addr_district":uploadBean?.district ?? "",
          "addr_province":uploadBean?.province ?? "",
          "address":uploadBean?.address ?? "",
          "adress":uploadBean?.address ?? "",
          "code": code ??"2828",
          "orgid":uploadBean?.orgid ?? "",
          "orglogo":uploadBean?.logo ?? "",
          "orgname":uploadBean?.oname ?? "",
          "otype":uploadBean?.otype ?? "",
          "otype":uploadBean?.otype ?? "",
          "phone":phone ?? "",
          "gps":uploadBean.gps??"",
        },
        callback: BaseCallback(onSuccess: (val) {
          UserResponseBean responseBean = UserResponseBean.fromMap(val);
          if(responseBean == null || responseBean.data == null || responseBean.data.authId == null){
            callback?.onError("数据返回报错～");
            VgEventBus.global.send(new ClearIndexCompanyInfoEvent(true));
            return;
          }
          if(responseBean?.data?.companyInfo?.isNeedForceLogout()??false){
            _doForceLogout();
            return;
          }
          String terCacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
          String homeCacheKey = UserRepository.getInstance().getHomeCompanyBaseInfoCacheKey();
          ///获取缓存数据
          SharePreferenceUtil.putString(terCacheKey, "");
          SharePreferenceUtil.putString(homeCacheKey, "");

          callback?.onSuccess(responseBean?.data);
          if(responseBean?.success??false){
            // autoLogin();
            VgEventBus.global.send(new ArtificialAttendanceUpdateEvent());
            // VgEventBus.global.send(new MonitoringIndexPageClass());
            Future.delayed(Duration(seconds: 0),(){
              CompanyDetailPage.navigatorPush(AppMain.context,uploadBean.gps);
              // RouterUtils?.popUntil(AppMain.context, "CompanyDetailPage");
            });
          }else{
            VgEventBus.global.send(new ClearIndexCompanyInfoEvent(true));
          }
          VgToastUtils.toast(context, "数据同步成功");
          // DefaultVgHud().hide(AppMain.context);
          VgHudUtils.hide(AppMain.context);
          // Future.delayed(Duration(milliseconds: 1000),(){
          // CompanyRegisterSuccessDialog.navigatorPushDialog(AppMain.context);
          // });
        }, onError: (msg) {
          VgEventBus.global.send(new ClearIndexCompanyInfoEvent(true));
          VgHudUtils.hide(AppMain.context);
          callback?.onError(msg);
        }));
  }

  void _doForceLogout(){
    UserRepository.getInstance().clearUserInfo();
    RouterUtils.popUntil(AppMain.context, AppMain.ROUTER,
        rootNavigator: false);
    CommonISeeDialog.navigatorPushDialog(AppMain.context, content: "您的企业已被注销或者审核被拒绝，无法继续使用，如有疑问请联系18665289540");
  }
}
